import logging

from redis.exceptions import RedisError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from django.db import DatabaseError

# 获取日志器对象,通过logger来打印日志
logger = logging.getLogger('django')


# 自定义异常处理
def exception_handler(exc, context):
    '''
    自定义异常处理
    :param exc: 异常的类型
    :param context: 一个字典包含requset,view
    :return: Response 响应对象
    '''

    # 调用drf的exception_handler 函数
    response = drf_exception_handler(exc, context)

    # 如果异常drf无法处理
    if response is None:
        # 获取异常的视图
        view = context.get('view')
        # 如果异常是databaserror类型的或者是rediserror类型的
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 日志记录
            logger.error('[%s]:%s' % (view, type(exc)))
            # 创建响应对象
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response
